import { defineStore } from "pinia";
import { ref, computed } from "vue";

export interface WordBank {
  id: string;
  name: string;
  words: string[];
}

export const useGameConfigStore = defineStore("gameConfig", () => {
  // 状态
  const roundTime = ref(
    localStorage.getItem("roundTime")
      ? parseInt(localStorage.getItem("roundTime")!)
      : 60
  );
  const wordBanks = ref<WordBank[]>(
    JSON.parse(localStorage.getItem("wordBanks") || "[]")
  );
  const selectedWordBankId = ref(
    localStorage.getItem("selectedWordBankId") || ""
  );

  // 计算属性
  const selectedWordBank = computed(() => {
    if (!selectedWordBankId.value) return null;
    return wordBanks.value.find((bank) => bank.id === selectedWordBankId.value);
  });

  // 方法
  const setRoundTime = (time: number) => {
    roundTime.value = time;
    localStorage.setItem("roundTime", time.toString());
  };

  const addWordBank = (wordBank: WordBank) => {
    wordBanks.value.push(wordBank);
    saveWordBanks();
  };

  const updateWordBank = (id: string, name: string, words: string[]) => {
    const index = wordBanks.value.findIndex((bank) => bank.id === id);
    if (index !== -1) {
      wordBanks.value[index] = { id, name, words };
      saveWordBanks();
    }
  };

  const deleteWordBank = (id: string) => {
    wordBanks.value = wordBanks.value.filter((bank) => bank.id !== id);
    if (selectedWordBankId.value === id) {
      selectedWordBankId.value = "";
      localStorage.removeItem("selectedWordBankId");
    }
    saveWordBanks();
  };

  const setSelectedWordBank = (id: string) => {
    selectedWordBankId.value = id;
    localStorage.setItem("selectedWordBankId", id);
  };

  const saveWordBanks = () => {
    localStorage.setItem("wordBanks", JSON.stringify(wordBanks.value));
  };

  return {
    roundTime,
    wordBanks,
    selectedWordBankId,
    selectedWordBank,
    setRoundTime,
    addWordBank,
    updateWordBank,
    deleteWordBank,
    setSelectedWordBank,
  };
});
